package ink.teamwork.battery.service

import ink.teamwork.battery.model.InviteResponse
import ink.teamwork.battery.model.LoginRequest
import ink.teamwork.battery.model.LoginResponse
import ink.teamwork.battery.model.Result
import ink.teamwork.battery.repository.CouponRepository
import ink.teamwork.battery.repository.UserRepository
import ink.teamwork.battery.util.BeanUtils
import ink.teamwork.battery.util.JSONUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Service
import java.time.LocalDateTime
import java.util.*

@Service
class UserService {

    @Autowired
    lateinit var wechatService: WechatService

    @Autowired
    lateinit var userRepository: UserRepository

    @Autowired
    lateinit var redisService: RedisService

    @Autowired
    lateinit var couponRepository: CouponRepository

    fun login(request: LoginRequest): Result {
        if (request.code.isEmpty()) {
            return Result.fail("code is empty")
        }

        if (request.code == "abc") {
            val list = userRepository.findAll()
            var user: User
            if (list.isEmpty()) {
                user = User()
                user.openId = "abc"
                user.nickname = "admin"
                user.unionId = "abc"
                user.sex = 1
                user.language = "zh_CN"
                user.city = "深圳"
                user.province = "广东"
                user.country = "中国"
                user.avatar = "https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJm0ibXxhxjwibXxhxjwibXxhxjwibXxhxjwibX"
                userRepository.save(user)
            } else {
                user = list[0]
            }
            user.accessToken = UUID.randomUUID().toString()
            redisService.set(user.openId, JSONUtils.toJSONString(user), 7 * 24 * 60 * 60)
            redisService.set(user.accessToken, user.openId, 7 * 24 * 60 * 60)
            return Result.success(LoginResponse(accessToken = user.accessToken))
        }

        val response = wechatService.getAccessToken(request.code)
        if (response.accessToken != null) {
            val info = wechatService.getUserInfo(response.accessToken!!, response.openId!!)
            if (info.errMsg == null) {
                val jsonUserStr = redisService.get(info.openId)
                var user: User
                if (jsonUserStr == null) {
                    val optional = userRepository.findById(response.openId)
                    if (optional.isPresent) {
                        user = optional.get()
                    } else {
                        user = BeanUtils.copy(info, User::class.java)
                        user.createdAt = LocalDateTime.now()
                        user.vid = request.vid ?: ""
                    }
                    user.updatedAt = LocalDateTime.now()
                    user.accessToken = UUID.randomUUID().toString()
                    userRepository.save(user)
                } else {
                    user = JSONUtils.jsonToBean(jsonUserStr, User::class.java)
                    user.accessToken = UUID.randomUUID().toString()
                }
                redisService.set(response.openId, JSONUtils.toJSONString(user), 7 * 24 * 60 * 60)
                return Result.success(LoginResponse(accessToken = user.accessToken))
            }
            return Result.fail(info.errMsg)
        }
        return Result.fail(response.errMsg)
    }

    fun getInviteList(vid: String): List<InviteResponse> {
        return BeanUtils.copy(
            userRepository.findAllByVid(vid, Sort.by(Sort.Order.desc("createdAt"))), InviteResponse::class.java
        )
    }

}